/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <bpf/libbpf.h>
#include "helloworld.skel.h"
#include "helloworld.h"

static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
{
	return vfprintf(stderr, format, args);
}

void read_trace_pipe(void)
{
	// int trace_fd;
	// #define DEBUGFS "/sys/kernel/debug/tracing/"
	// trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
	// if (trace_fd < 0)
	// 	return;

	// while (1) {
	// 	static char buf[4096];
	// 	ssize_t sz;

	// 	sz = read(trace_fd, buf, sizeof(buf));
	// 	if (sz > 0) {
	// 		buf[sz] = 0;
	// 		puts(buf);
	// 	}
	// }
	system("cat /sys/kernel/debug/tracing/trace_pipe");
}


int main(int argc, char **argv)
{
	struct helloworld_bpf *skel;
	int err;
	pid_t pid;
	unsigned int index = 0;
	struct bpf_transfer value = {};
	/* Set up libbpf errors and debug info callback */
	libbpf_set_print(libbpf_print_fn);

	/* Load and verify BPF application */
	skel = helloworld_bpf__open_and_load();
	if (!skel) {
		fprintf(stderr, "Failed to open and load BPF skeleton\n");
		return 1;
	}

	/* ensure BPF program only handles write() syscalls from our process */
	pid = getpid();
	// err = bpf_map__update_elem(skel->maps.my_pid_map, &index, sizeof(index), &pid,
	// 			   sizeof(pid_t), BPF_ANY);
	// if (err < 0) {
	// 	fprintf(stderr, "Error updating map with pid: %s\n", strerror(err));
	// 	goto cleanup;
	// }

	/* Attach tracepoint handler */
	err = helloworld_bpf__attach(skel);
	if (err) {
		fprintf(stderr, "Failed to attach BPF skeleton\n");
		goto cleanup;
	}

	printf("Successfully started! Please run `sudo cat /sys/kernel/debug/tracing/trace_pipe` "
	       "to see output of the BPF programs.\n");

	// for (;;) {
	// 	/* trigger our BPF program */
	// 	fprintf(stderr, ".");
	// 	sleep(1);
	// }
	read_trace_pipe();

	// for(;;){
	// 	err = bpf_map__lookup_elem(skel->maps.my_data_map, &index, sizeof(index), &value, sizeof(value), NULL);
	// 	if (err)
	// 	{
	// 		sleep(1);
	// 		continue;
	// 	}
	// 	printf("pid = %d, count = %d\n",value.pid, value.count);
	// }

cleanup:
	helloworld_bpf__destroy(skel);
	return -err;
}
